<?php

namespace app\mobile\controller;

use app\common\controller\ActionLogs;
use app\common\controller\Platurl;
use app\common\model\CardFreecard;
use app\common\model\CardGeneral;
use app\common\model\CardGoods;
use app\common\model\CardMember;
use app\common\model\CardOrder;

use app\common\model\CardPaycard;
use app\common\model\CardPaycardlog;
use app\common\model\CardUserGet;

use app\common\model\Agent;
use app\common\model\CardUserUpdate;
use app\common\model\Paylog;
use app\common\model\WxOpen;
use app\common\model\Merchant;
use app\common\model\System;
use think\Config;
use think\Controller;
use think\Request;
use think\Session;
use Wechat\Wxobjopen;

class Cardshopnu extends Mobiletest
{

//    public function orderconf($id){
//        $map['id'] = $id;
//        $CardGoods = new CardGoods();
//        $list =$CardGoods->where($map)->order('id asc')->select();
//        $this->assign('list', $list);
//        return $this->fetch();
//    }




    private function cardpaylogadd($cinfo, $openid)
    {
        $orderid = $cinfo['orderid'];
        $data['mid'] = $cinfo['mid'];
        $data['openid'] = $openid;
        $data['orderid'] = $orderid;
        $data['price'] = $cinfo['price'];
        $data['cid'] = $cinfo['id'];
        $data['user_code'] = $cinfo['user_code'];
        $CardPaycardlog = new CardPaycardlog();
        $add = $CardPaycardlog->save($data);
        $data['orderid'] = $orderid;
        $data['mid'] = $cinfo['mid'];
        $data['openid'] = $openid;
        $data['pay_statu'] = 0;
        $data['price'] = $cinfo['price'];
        $data['yf_price'] = $cinfo['price'];
        $data['zk_price'] = $data['yf_price'] - $data['price'];
        $data['add_time'] = time();
        $data['attach'] = 'ffcardbuy';
        $data['cz_card_id'] = $cinfo['card_id'];
        $Paylog = new Paylog();
        $add = $Paylog->allowField(true)->save($data);
    }

    //获取用户code
    public function res_user_code($arr)
    {
        $options = $this->options($arr['card_id']);
        $WxObj = new Wxobjopen($options);
        $codedata['encrypt_code'] = $arr['encrypt_code'];
        $resc = $WxObj->decryptCode($codedata);

        if ($resc['errcode'] == 0) {
            if ($resc['code'] == '') {
                $usercode = "";
            } else {
                $usercode = $resc['code'];
            }
            return $usercode;
        }
    }

    //付费购券列表
    public function paycards()
    {
        $this->_init();
        $arr = request()->param();
        $CardPaycard = new CardPaycard();
        if (isset($arr['card_id'])) {
            $appid = $this->getappid($arr['card_id']);
            $card_id = $arr['card_id'];
            $top_mid = $this->gettopmid($card_id);
        } else {
            $appid = $this->getappidmid($arr['mid']);
            $card_id = $this->get_cardid_mid($arr['mid']);
            $top_mid = $this->get_top_mid($arr['mid']);
        }
        $map['top_mid'] = $top_mid;
        $map['status'] = 1;
        $map['type'] = 2;
        $list = $CardPaycard->where($map)->select();
        $card['logo_url'] = cardgetinfo($card_id, 0, 0);
        $card['card_id'] = $card_id;
        $this->assign('card', $card);
        $this->assign('list', $list);
        return $this->fetch();
    }

    //付费购券详情
    public function paycardsinfo()
    {
        $arr = request()->param();
        $this->_init();
        if (isset($arr['card_id'])) {
            $appid = $this->getappid($arr['card_id']);
            $card_id = $arr['card_id'];
        } else {
            $appid = $this->getappidmid($arr['mid']);
            $card_id = $this->get_cardid_mid($arr['mid']);
        }
        $openid = Session::get($appid . '_openid');
//        var_dump($card_id);
        $user['id'] = '0';
        $user['card_id'] = $card_id;
        $user['openid'] = $openid;
        $user['code'] = 'public';
//        if ($user) {
            $CardPaycard = new CardPaycard();
            $id = request()->param('fid');
            $map['id'] = $id;
            $map['status'] = 1;
            $info = $CardPaycard->where(array('id' => $id))->find();
            $cardlist = json_decode($info['cardlist'], true);;
            $CardGeneral = new CardGeneral();
            foreach ($cardlist as $k => $v) {
                $cards = $CardGeneral->where(['card_id' => $v['zs_card_id']])->field('color,title,card_id,mid,top_mid,card_type,brand_name,end_timestamp,begin_timestamp')->find();
                $cardlist[$k]['title'] = $cards['title'];
                $cardlist[$k]['color'] = $cards['color'];
                $cardlist[$k]['card_id'] = $cards['card_id'];
                $cardlist[$k]['mid'] = $cards['mid'];
                $cardlist[$k]['top_mid'] = $cards['top_mid'];
                $cardlist[$k]['brand_name'] = $cards['brand_name'];
                $cardlist[$k]['card_type'] = $cards['card_type'];
                $cardlist[$k]['begin_timestamp'] = $cards['begin_timestamp'];
                $cardlist[$k]['end_timestamp'] = $cards['end_timestamp'];
            }
        $info['stocks'] = $info['num'] - $info['get_num'];
            $card['card_id'] = $card_id;
            $this->assign('card', $card);
            $this->assign('user', $user);
            $this->assign('cardlist', $cardlist);
            $this->assign('info', $info);
            return $this->fetch();
//        } else {
//            return $this->fetch('off');
//        }
    }

    //付费会员卡
    public function paycardusinfo()
    {

        return $this->fetch();
    }


    //免费券列表
    public function freecards()
    {
        $this->_init();
        $arr = request()->param();
        $CardFreecard = new CardFreecard();
        if (isset($arr['card_id'])) {
//            $appid = $this->getappid($arr['card_id']);
            $card_id = $arr['card_id'];
            $top_mid = $this->gettopmid($card_id);
        } else {
//            $appid = $this->getappidmid($arr['mid']);
            $card_id = $this->get_cardid_mid($arr['mid']);
            $top_mid = $this->get_top_mid($arr['mid']);
        }
        $map['top_mid'] = $top_mid;
        $map['status'] = 1;
        $map['type'] = 1;
        $map['is_del'] = 1;
        $map['is_follow'] = 0;
        $map['is_shop_show']="Y";
        $list = $CardFreecard->where($map)->select();
        $card['logo_url'] = cardgetinfo($card_id, 0, 0);
        $card['card_id'] = $card_id;
        $this->assign('card', $card);
        $this->assign('list', $list);
        return $this->fetch();
    }

    //免费券详情
    public function freecardsinfo(){
        $arr = request()->param();
        $this->_init();
        if (isset($arr['card_id'])) {
            $appid = $this->getappid($arr['card_id']);
            $card_id = $arr['card_id'];
        } else {
            $appid = $this->getappidmid($arr['mid']);
            $card_id = $this->get_cardid_mid($arr['mid']);
        }
        $openid = Session::get($appid . '_openid');
//        var_dump($card_id);
        $user['id'] = '0';
        $user['card_id'] = $card_id;
        $user['openid'] = $openid;
        $user['code'] = 'public';
//        if ($user) {
        $CardFreecard = new CardFreecard();
        $id = request()->param('fid');
        $map['id'] = $id;
        $map['status'] = 1;

        $info = $CardFreecard->where(array('id' => $id,'is_shop_show'=>"Y"))->find();
        if($info){
        $cardlist = json_decode($info['cardlist'], true);;
        $CardGeneral = new CardGeneral();
        foreach ($cardlist as $k => $v) {
            $cards = $CardGeneral->where(['card_id' => $v['zs_card_id']])->field('color,title,card_id,mid,top_mid,card_type,brand_name,end_timestamp,begin_timestamp')->find();
            $cardlist[$k]['title'] = $cards['title'];
            $cardlist[$k]['color'] = $cards['color'];
            $cardlist[$k]['card_id'] = $cards['card_id'];
            $cardlist[$k]['mid'] = $cards['mid'];
            $cardlist[$k]['top_mid'] = $cards['top_mid'];
            $cardlist[$k]['brand_name'] = $cards['brand_name'];
            $cardlist[$k]['card_type'] = $cards['card_type'];
            $cardlist[$k]['begin_timestamp'] = $cards['begin_timestamp'];
            $cardlist[$k]['end_timestamp'] = $cards['end_timestamp'];
        }

        $card['card_id'] = $card_id;
        $this->assign('card', $card);
        $this->assign('user', $user);
        $this->assign('cardlist', $cardlist);
        $this->assign('info', $info);
        return $this->fetch();
        }else{
            $this->error("该商品不存在");
        }
    }

    //订单详情
    /*
     * 订单id 会员卡$card_id
     *
     * $id $card_id
     */
    public function orderinfo($id, $card_id)
    {
        $this->_init();
        $appid = $this->getappid($card_id);
        $map['card_id'] = $card_id;
        $map['openid'] = Session::get($appid . '_openid');
        $map['have'] = 1;
        $map['card_type'] = 'MEMBER_CARD';
        $CardUserGet = new CardUserGet();
        $info = $CardUserGet->where($map)->find();
        if ($info) {
            $mab['openid'] = Session::get($appid . '_openid');
            $mab['card_id'] = $card_id;
            $mab['id'] = $id;
            $CardGoods = new CardGoods();
            $CardOrder = new CardOrder();
            $order = $CardOrder->where($mab)->find();
            $goods = $CardGoods->where('id', $order['gid'])->find();
            $this->assign('goods', $goods);
            $this->assign('order', $order);
            return $this->fetch();
        } else {
            $this->redirect('Carduser/weboff', ['card_id' => $card_id]);
        }
    }


    //分享jssdk
    /*
     * $card_id
     */
    private function getsharejssdk($arr)
    {
//        return $arr;
        $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        $options = $this->options($arr);
        //分享
        $weObj = new Wxobjopen($options);
        $jssdk = $weObj->getJsSign($url);
        $wxJsSdk = [
            'debug' => false,
            'appId' => $jssdk['appId'],
            'timestamp' => $jssdk['timestamp'],
            'nonceStr' => $jssdk['nonceStr'],
            'signature' => $jssdk['signature'],
            'jsApiList' => [
                'onMenuShareTimeline',
                'onMenuShareAppMessage',
                'onMenuShareQQ',
                'onMenuShareQZone',
                'closeWindow',
                'hideAllNonBaseMenuItem',
            ]
        ];
        return $wxJsSdk;
    }

    public function paycardpay()
    {
        try{
            $arr = request()->param();
//        return json($arr);
            $Merchant = new Merchant();
            $Agent = new Agent();
            $WxOpen = new WxOpen();
            $id = request()->param('id');
            $CardPaycardlog = new CardPaycardlog();
            $cinfo = $CardPaycardlog->relation('Paycardinfo')->where(array('id' => $id))->find();


            $map['id'] = $cinfo['mid'];
            $config = $Merchant->where($map)->find();
            $agent = $Agent->where(array('id' => $config['agent']))->find();
            $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();
            $userwx = $WxOpen->where(array('id' => $config['wx_open_id']))->find();

            $options = array(
                'appid' => $users['authorizer_appid'], // 填写高级调用功能的app id
                'partnerid' => $agent['partnerid'], // 财付通商户身份标识
                'partnerkey' => $agent['partnerkey'], // 财付通商户权限密钥Key
            );
            $weObj = new Wxobjopen($options);
            $price = $cinfo['price'];
            $appid = $users['authorizer_appid'];
            $mch_id = $agent['partnerid'];
            $out_trade_no = $cinfo['orderid'];
            $body = "付费券购买";
            $sub_mch_id = $config['sub_mch_id'];
            $sub_appid = $userwx['authorizer_appid'];
            $total_fee = $price * 100;

            $sub_openid = $cinfo['openid'];
            $notify_url = 'https://' . $_SERVER ['SERVER_NAME'] . '/api.php';
            $spbill_create_ip = $_SERVER["REMOTE_ADDR"];
            $nonce_str = $weObj->generateNonceStr();
            $partnerkey = $options['partnerkey'];
            $arrdata = array(
                "appid" => $appid,
                'sub_appid' => $sub_appid,
                "mch_id" => $mch_id,
                "sub_mch_id" => $sub_mch_id,
                "nonce_str" => $nonce_str,
                "body" => $body,
                "out_trade_no" => $out_trade_no,
                "total_fee" => $total_fee,
                "spbill_create_ip" => $spbill_create_ip,
                "notify_url" => $notify_url,
                "sub_openid" => $sub_openid,
                'trade_type' => 'JSAPI'
            );
            $pay_xml = $weObj->createWxPackageXmls($arrdata,$partnerkey);
            $pay_xml = $weObj->get_pay_id($pay_xml);

            if ($pay_xml['return_code'] == 'SUCCESS') {
                $prepay_id = $pay_xml['prepay_id'];
                $jsApiObj["appId"] = $appid;
                $timeStamp = time();
                $jsApiObj["timeStamp"] = "$timeStamp";
                $jsApiObj["nonceStr"] = $nonce_str;
                $jsApiObj["package"] = "prepay_id=" . $prepay_id;
                $jsApiObj["signType"] = "MD5";
                $jsApiObj["paySign"] = $weObj->getPaySignature($jsApiObj);
                //状态码
                $this->assign('jsApiObj', json_encode($jsApiObj, JSON_UNESCAPED_UNICODE));
            } else {
                $this->error('系统错误:' . $pay_xml['return_msg']);

            }
            $arr = request()->param();
            if (isset($arr['card_id'])) {
                $appid = $this->getappid($arr['card_id']);
                $card_id = $arr['card_id'];
            } else {
                $appid = $this->getappidmid($arr['mid']);
                $card_id = $this->get_cardid_mid($arr['mid']);
            }
            $card['card_id'] = $card_id;
            $card['logo_url'] = cardgetinfo($card['card_id'], 0, 0);
            $this->assign('card', $card);
            $this->assign('cinfo', $cinfo);
//        var_dump(json_encode($cinfo,JSON_UNESCAPED_UNICODE));
            return $this->fetch();
        }catch (\Exception $e){
//            $ActionLogs=new ActionLogs();
//            $ActionLogs->writelog("payos","cardget","getfreecards","e:",$e->getMessage());
            echo "<div style='margin-top:30%;font-size: 70px;text-align: center '>系统繁忙，请稍后再试！！！</div>";
        }
    }

    public function addorder()
    {
        if (request()->isAjax()) {
//            return json(request()->post());

            $id = request()->post('id');
            if (get_is_paycardnum($id) == false) {
                return ['code' => 9003, 'message' => '该商品没有库存'];
            }
            $CardPaycard = new CardPaycard();
            $cinfo = $CardPaycard->where(array('id' => $id))->find();
            $buycount = $this->getxg($cinfo['id'], request()->post('openid'));
            if ($cinfo['homebuy'] <= $buycount) {
                return ['code' => 9004, 'message' => '该商品限购' . $cinfo['homebuy'] . "件，您已购买" . $buycount . "件"];
            }

            $orderid = $this->getorderid($cinfo['mid']);
            $data['mid'] = $cinfo['mid'];
            $data['openid'] = request()->post('openid');
            $data['orderid'] = $orderid;
            $data['price'] = $cinfo['price'];
            $data['fid'] = $cinfo['id'];
            $CardPaycardlog = new CardPaycardlog();
            $add = $CardPaycardlog->save($data);
            $data['orderid'] = $orderid;
            $data['mid'] = $cinfo['mid'];
            $data['openid'] = request()->post('openid');
            $data['pay_statu'] = 0;
            $data['price'] = $cinfo['price'];
            $data['yf_price'] = $cinfo['price'];
            $data['zk_price'] = $data['yf_price'] - $data['price'];
            $data['add_time'] = time();
            $data['attach'] = 'ffcardnu';
            $data['cz_card_id'] = request()->post('get_card_id');
            $Paylog = new Paylog();
            $add = $Paylog->allowField(true)->save($data);
            if ($add) {
                $data2['code'] = 0;
                $CardUserGet = new CardUserGet();
                $card_id = $CardUserGet->where(['id' => request()->post('get_card_id')])->value('card_id');
                if (!$card_id){
                    $card_id = $this->get_cardid_mid($cinfo['mid']);
                }
                $data2['data']['url'] = url('Cardshopnu/paycardpay', array('id' => $CardPaycardlog->id, 'card_id' => $card_id));
//                $data2['data']['url'] = url('Cardshop/paycardpay', array('id' => $CardPaycardlog->id));
            } else {
                $data2['code'] = 9001;
                $data2['data']['message'] = "操作失败";
            }
            return json($data2);
        }


    }

    public function getxg($fid, $openid)
    {
        $map['paystatu'] = 1;
        $map['fid'] = $fid;
        $map['openid'] = $openid;
        $CardPaycardlog = new CardPaycardlog();
        $count = $CardPaycardlog->where($map)->count('id');
        return $count;


    }

    public function paysuccess()
    {
        if (request()->isAjax()) {
            $request = request();
            $Merchant = new Merchant();
            $Agent = new Agent();
            $WxOpen = new WxOpen();
            $map['id'] = $request->post('id');
            $config = $Merchant->where($map)->find();
            $agent = $Agent->where(array('id' => $config['agent']))->find();
            $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();
            $userwx = $WxOpen->where(array('id' => $config['wx_open_id']))->find();
            $options = array(
                'appid' => $users['authorizer_appid'], // 填写高级调用功能的app id
                'partnerid' => $agent['partnerid'], // 财付通商户身份标识
                'partnerkey' => $agent['partnerkey'], // 财付通商户权限密钥Key
            );
            $weObj = new Wxobjopen($options);
            $appid = $users['authorizer_appid'];
            $mch_id = $agent['partnerid'];
            $out_trade_no = $request->post('orderid');
            $nonce_str = $weObj->generateNonceStr();
            $sub_mch_id = $config['sub_mch_id'];
            $sub_appid = $userwx['authorizer_appid'];
            $pay_xml = $weObj->createOrderXml($appid, $mch_id, $sub_appid, $sub_mch_id, $out_trade_no, $nonce_str);
            $payorder_xml = $weObj->getPayNum($pay_xml);
            $pay_zt = $payorder_xml['trade_state'];
            if ($pay_zt == "SUCCESS") {
                $data['code'] = 0;
                $CardPaycardlog = new CardPaycardlog();
                $Paylog = new Paylog();
//                $getcardid = $Paylog->where(['orderid' => $out_trade_no])->value('cz_card_id');
                $arr['mid'] = $CardPaycardlog->where(['orderid' => $out_trade_no])->value('mid');
                $arr['give_rec_id'] = $CardPaycardlog->where(['orderid' => $out_trade_no])->value('id');
                $data['code'] = 0;
                $data['data']['url'] = $this->getpaycardurl($arr);
            } else {
                $data['code'] = 1;
            }
            return json($data);
        }

    }

    //获取card_id
    private function getcardid($id)
    {
        $CardUserGet = new CardUserGet();
        $card_id = $CardUserGet->where(['id' => $id])->value('card_id');
        return $card_id;
    }

    //付费购券领取链接
    private function getpaycardurl($arr)
    {
        $Merchant = new Merchant();
        $top_mid = $Merchant->where(array('id'=>$arr['mid']))->value('top_mid');
        $Platurl = new Platurl();
        $notify_url = $Platurl->getagenturl('top_mid', $top_mid);
        $url = $notify_url . '/mobile.php?s=/cardget/getpaycards/mid/' . $arr['mid'] . '/rec_id/' . $arr['give_rec_id'];
        return $url;
    }

    private function getorderid($sh)
    {
        $order = "H" . $sh . "-" . date('YmdHis') . rand(10000, 99999);
        return $order;

    }


}
